package com.local.web.controller;


import com.local.cart.pojo.ShoppingCart;
import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.PageResultUtil;
import com.local.common.util.ResultUtil;
import com.local.order.pojo.Order;
import com.local.order.pojo.OrdersRequestParam;
import com.local.user.pojo.User;
import com.local.web.constants.WebConstants;
import com.local.web.service.OrderService;
import com.local.web.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@Controller
public class OrderController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    @Autowired
    private OrderService orderService;

    /**
     * 提交订单
     *
     * @param userCouponRecordId
     * @param session
     * @return
     */
    @GetMapping("/order/save")
    public String saveOrder(@RequestParam(name = "userCouponRecordId", required = false) Integer userCouponRecordId, HttpSession session) {
        User user = (User) session.getAttribute(WebConstants.WEB_USER_SESSION_KEY);
        if (user.getAddress().isEmpty()) {
            throw new BusinessException(
                    ExceptionCodeEnum.ORDER_SAVE_ADDRESS_EMPTY.getCode(),
                    ExceptionCodeEnum.ORDER_SAVE_ADDRESS_EMPTY.getMessage()
            );
        }

        List<ShoppingCart> shoppingCartList = shoppingCartService.getListByUserId(session, user.getUserId());
        if (shoppingCartList.size() == 0) {
            //购物车无商品，请先添加商品至购物车
            throw new BusinessException(
                    ExceptionCodeEnum.ORDER_SAVE_CART_EMPTY.getCode(),
                    ExceptionCodeEnum.ORDER_SAVE_CART_EMPTY.getMessage()
            );
        }

        //生成订单
        String orderNo = orderService.saveOrder(user, shoppingCartList, userCouponRecordId);

        return "redirect:/order/" + orderNo;
    }


    @GetMapping("/order/{orderNo}")
    public String orderDetail(@PathVariable("orderNo") String orderNo, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(WebConstants.WEB_USER_SESSION_KEY);
        ResultUtil<Order> orderResult = orderService.getOrderByOrderNo(orderNo);
        if (orderResult.getCode() != 200) {
            throw new BusinessException(orderResult.getCode(), orderResult.getMessage());
        }
        Order order = orderResult.getData();
        if (Objects.isNull(order)) {
            throw new BusinessException(orderResult.getCode(), orderResult.getMessage());
        }
        if (!(user.getUserId().equals(order.getUserId()))) {
            throw new BusinessException(
                    ExceptionCodeEnum.ORDER_AUTH_NO_USER_OWN.getCode(),
                    ExceptionCodeEnum.ORDER_AUTH_NO_USER_OWN.getMessage()
            );
        }

        request.setAttribute("order", order);
        return "mall/order-detail";
    }


    @GetMapping({"/orders", "/orders/page/{page}"})
    public String orders(HttpServletRequest request, @PathVariable(name = "page", required = false) Integer page) {
        User user = (User) request.getSession().getAttribute(WebConstants.WEB_USER_SESSION_KEY);

        page = Objects.isNull(page) || page <= 0 ? 1 : page;
        OrdersRequestParam ordersRequestParam = new OrdersRequestParam(user.getUserId(), page, 3, 0);
        ResultUtil<PageResultUtil<Order>> ordersResult = orderService.orders(ordersRequestParam);
        if (ordersResult.getCode() != 200) {
            throw new BusinessException(ordersResult.getCode(), ordersResult.getMessage());
        }

        request.setAttribute("orderPageResult", ordersResult.getData());
        request.setAttribute("path", "order-index");

        return "mall/order-index";
    }
}
